<script setup lang="ts">
import { uploadAPI } from "@/apis/common";
import {
  createRentAPI,
  deleteEnterpriseAPI,
  deleteRentAPI,
  getBuildingListAPI,
  getEnterpriseListAPI,
  getRentListAPI,
  outRentAPI,
} from "@/apis/enterprise";
import type {
  Datum,
  EmptyObject,
  Enterprise,
  EnterpriseListParams,
  RentBuilding,
} from "@/types/enterprise";
import { ElMessage, ElMessageBox, type FormInstance, type FormRules, type UploadRawFile, type UploadRequestOptions } from "element-plus";
import { ref, watch } from "vue";

// 请求参数
const params = ref<EnterpriseListParams>({
  page: 1,
  pageSize: 2,
  name: "", // 企业名称
});
// 企业列表
const list = ref<ExpandRow[]>([]);
// 总记录数
const total = ref(0);

const getList = async () => {
  const res = await getEnterpriseListAPI(params.value); // 获取企业列表
    //map映射数据用于前端展示
    list.value = res.data.rows.map(item=>({
    ...item,
    rentList:[]// 合同列表默认值，用于嵌套表格渲染
  }))

  total.value = res.data.total 
};

getList();

//查询
const getOnList = () => {
  params.value.page = 1; // 页码
  getList(); // 获取企业列表
};

//删除企业
const deleteEnterprise = async (id: string) => {
  // 弹出确认框
  const confirm = await ElMessageBox.confirm("确定要删除该企业吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  });
  if (confirm === "confirm") {
    await deleteEnterpriseAPI(id);
    ElMessage.success("删除企业成功");
    getList();
  }
};

//添加合同
const rentDialogVisible = ref(false);
//弹出添加合同弹窗
const addRent = async (id:number) => {
  rentDialogVisible.value = true;
    // 获取可租赁楼宇列表
  const res = await getBuildingListAPI()
  buildingList.value = res.data
  // 保存企业id，用于添加合同
  rentForm.value.enterpriseId = id
};


//关闭添加合同弹窗
const closeDialog = () => {
  rentDialogVisible.value = false;
};



// 添加合同 - 表单校验
const rentRules = ref<FormRules<EmptyObject>>({
  buildingId: [{ required: true, message: "请选择楼宇", trigger: "blur" }],
  endTime: [{ required: true, message: "请选择租赁日期", trigger: "blur" }],
  contractId: [{ required: true, message: "请上传合同文件" }],
});

// 获取楼宇列表
const buildingList = ref<RentBuilding[]>([]);
const getBuildingList = async () => {
  rentDialogVisible.value = false;
  // 获取楼宇列表
  const res = await getBuildingListAPI();
  buildingList.value = res.data;
};

getBuildingList();


//日期选择器禁用时间
const timeArr = ref<string[]>([])
watch(timeArr, (val)=>{
if(val){
  rentForm.value.startTime = val[0]
  rentForm.value.endTime = val[1]
}else{
  rentForm.value.startTime = ''
  rentForm.value.endTime = ''
}
},{deep:true})

//通过disabledDate 禁用时间
const disabledDate = (time:Date)=>{
    // 不能小于今日日期，包含今天 （ 1000 * 60 * 60 * 24 -> 1天的毫秒数 ）
    return time.getTime() < Date.now() - 1000 * 60 * 60 * 24
}

//上传文件
const addFormRef = ref<FormInstance>()

//上传合同文件
const onUploadRequest = async(options:UploadRequestOptions)=>{
  //1.准备FormData对象
  const fd = new FormData()
  fd.append('file',options.file)//文件对象
  fd.append('type','enterprise')//租赁合同附件
  //2.发送请求，上传文件
  const res =await uploadAPI(fd)
  //3.保存合同附件url和id。用于添加合同
  rentForm.value.contractUrl = res.data.url
  rentForm.value.contractId = res.data.id
  //4. 主动触发校验(如果校验通过，会清除错误信息)
  addFormRef.value?.validateField('contractId')
    // 5. return 后端返回的数据，保存到 response 中
    return res.data
}

//删除上传文件
const removeUpload = ()=>{
  //情况数据
  rentForm.value.contractUrl = ''
  rentForm.value.contractId = undefined
  //触发校验
  addFormRef.value?.validateField('contractId')
}

//上传文件前校验
const beforeUpload = (rawFile:UploadRawFile)=>{
    // size 的单位是 Byte，5M = 5 * 1024 * 1024
    const allowSize =  5 * 1024 * 1024
  // 检测文件大小
  if(rawFile.size > allowSize){
    ElMessage.error('文件过大, 请上传5M以下的文件')
    return false
  }
  return true
}

//添加合同
const handleAddRent = async ()=>{
  try{
    //1.校验表单
    await addFormRef.value?.validate()
    //2.发送请求
    await createRentAPI(rentForm.value)
    //3.轻提示 
    ElMessage.success('添加合同成功')
    //4.关闭弹窗
    closeRent()
  }catch{

  }
}




//表单数据默认值
const initRentForm = ()=>{
  return{
    buildingId: undefined, // 租赁楼宇id
    startTime: "", // 开始日期（不能小于今日日期）
    endTime: "", // 租赁结束日期
    contractUrl: "", // 合同附件url
    contractId: undefined, // 合同附件id
    type: 0, // 操作类型，添加合同0，续签合同1
    enterpriseId: undefined, // 企业id
  }
}

//添加合同-表单数据
const rentForm = ref<EmptyObject>(initRentForm())

const fileList = ref<UploadRawFile[]>([])
//关闭弹窗，重置表单
const closeRent = ()=>{
  rentDialogVisible.value = false//关闭弹窗
  addFormRef.value?.resetFields()//清空表单
  timeArr.value = []//清空时间
  fileList.value = []//清空文件列表
  rentForm.value = initRentForm()//重置表单
}


//前端自定义的类型，用于展示嵌套表格
interface ExpandRow extends Enterprise{
  //合同列表
  rentList: Datum[]
}





// 展开行或折叠行时触发
const onExpandChange =async (row: ExpandRow) => {
   // 根据企业 id 获取合同列表
      const res = await getRentListAPI(row.id)
      // 把合同列表添加到企业信息中
      row.rentList = res.data
}


//退租
const outRent = (row: Datum)=>{
  ElMessageBox.confirm('确定要退租吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async()=>{
    await outRentAPI(row.id)
    row.status = 3
    ElMessage.success('退租成功')
  }).catch(()=>{})
}


// 删除合同（合同Row, 企业Row）
const deleteRent = async (rentRow: Datum, enterPriseRow: Enterprise) => {
  ElMessageBox.confirm('是否确认删除当前合同?', '温馨提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    // 发送请求，更新后端合同状态(后端)
    await deleteRentAPI(rentRow.id)
    // 删除过滤掉合同（前端）
    enterPriseRow.rentList = enterPriseRow.rentList.filter((item: Datum) => item.id !== rentRow.id)
    // 轻提示
    ElMessage.success('删除成功')
  }).catch(() => {
    // 点击取消，什么也不做
  })


}

</script>

<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model="params.name"
        @clear="getOnList()"
      />
      <el-button type="primary" @click="getOnList()">查询</el-button>
    </div>
    <div class="create-container">
      <el-button type="primary" @click="$router.push('/exterpriseAdd')"
        >添加企业</el-button
      >
    </div>
    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="list" @expand-change="onExpandChange" row-key="id">
         <!-- type="expand" 显示一个可展开的按钮 -->
          <el-table-column type="expand">
            <template #default="{row}">
              <el-table :data="row.rentList">
                <el-table-column label="租赁楼宇" width="320" prop="buildingName" />
                <el-table-column label="租赁起始时间" prop="startTime" />
                <el-table-column label="合同状态" prop="status" >
                  <!-- 合同的租赁状态 0待生效 1生效中 2已到期 3已退租 -->
                    <template v-slot="{row}">
                      <el-tag type="warning" v-if="row.status === 0">待生效</el-tag>
                      <el-tag type="success" v-else-if="row.status === 1">生效中</el-tag>
                      <el-tag type="info" v-else-if="row.status === 2">已到期</el-tag>
                      <el-tag type="danger" v-else-if="row.status === 3">已退租</el-tag>
                    </template>
                </el-table-column>
                <el-table-column label="操作" width="300">
                  <template v-slot="{row:rentRow}">
                    <el-button size="small" type="text">续租</el-button>
                    <el-button size="small" type="text" :disabled="row.status === 3"   @click="outRent(rentRow)">退租</el-button>
                    <el-button size="small" type="text" :disabled="row.status === 3"  @click="deleteRent(rentRow, row)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </template>
          </el-table-column>
        <el-table-column type="index" label="序号" width="120" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="phone" />
        <el-table-column label="操作" width="300">
          <template v-slot="{ row }">
            <el-button size="small" type="text" @click="addRent(row.id)"
              >添加合同</el-button
            >
            <el-button size="small" type="text" @click="$router.push(`/exterpriseDetail/${row.id}`)">查看</el-button>
            <el-button
              size="small"
              type="text"
              @click="$router.push(`/exterpriseAdd/${row.id}`)"
              >编辑</el-button
            >
            <el-button
              size="small"
              type="text"
              @click="deleteEnterprise(row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page-container">
      <el-pagination
        :total="total"
        layout="total, prev, pager, next,jumper,sizes"
        :page-sizes="[2, 4, 6, 8, 10]"
        v-model:page-size="params.pageSize"
        v-model:current-page="params.page"
        @change="getList()"
      />
    </div>
    <el-dialog
              @close="closeRent"
              v-model="rentDialogVisible"
              title="添加合同"
              width="600px"
            >
              <div class="form-container">
                <el-form
                  ref="addForm"
                  :model="rentForm"
                  :rules="rentRules"
                  label-position="top"
                >
                  <el-form-item label="租赁楼宇" prop="buildingId">
                    <el-select
                      v-model="rentForm.buildingId"
                      placeholder="请选择"
                      clearable
                    >
                      <el-option
                        v-for="item in buildingList"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="租赁起止日期" prop="endTime">
                    <el-date-picker
                      v-model="timeArr"
                      type="daterange"
                      range-separator="至"
                      start-placeholder="开始日期"
                      end-placeholder="结束日期"
                      value-format="YYYY-MM-DD"
                      :disabled-date="disabledDate"
                    />
                  </el-form-item>
                  <el-form-item label="租赁合同" prop="contractId">
                    <el-upload 
                    v-model:file-list="fileList"
                    accept=".doc, .pdf"
                    :http-request="onUploadRequest"
                    @remove="removeUpload"
                    :before-upload="beforeUpload"
                    >
                      <el-button size="small" type="primary" plain
                        >上传合同文件</el-button
                      >
                      <template #tip>
                        <div class="el-upload__tip">
                          支持扩展名：.doc .pdf, 文件大小不超过5M
                        </div>
                      </template>
                    </el-upload>
                  </el-form-item>
                </el-form>
              </div>
              <template #footer>
                <el-button  @click="closeDialog">取消</el-button>
                <el-button type="primary" @click="handleAddRent">确定</el-button>
              </template>
            </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.building-container {
  padding: 20px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}

.create-container {
  margin: 10px 0px;
}

.page-container {
  padding: 4px 0px;
  text-align: right;
}

.form-container {
  padding: 0px 80px;
}
</style>
